<?php
/**
 * 新人专区B端用户操作
 */
namespace Beerus\Modules\NewbornZone\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\DecoCompanyAuth;
use Doraemon\model\DesignerAuth;
use Doraemon\service\Member as sMember;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\Activity\NewbornZone\NewbornZoneBCity as mNewbornZoneBCity;
use Doraemon\model\Activity\NewbornZone\NewbornZoneBUser as mNewbornZoneBUser;
use Doraemon\model\Activity\NewbornZone\NewbornZoneWelfareInfo as mNewbornZoneWelfareInfo;
use Doraemon\model\Member as mMember;
use Illuminate\Support\MessageBag;

class BUserController extends Controller {
    const PAGE_SIZE = 20;

    public function index(Request $request, Content $content) {
        $cityList = mNewbornZoneBCity::getAllCityList();
        $gridModel = new pGridDataModel($cityList);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disableFilter();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();

                $grid->column('id', '配置ID');
                $grid->column('city', '服务地区');
                $grid->column('designer_num', '设计师用户数');
                $grid->column('deco_num', '装修公司用户数');
                $grid->column('edit_time', '最近一次修改时间')->display(function () {
                    return date('Y-m-d H:i:s', $this->edit_time);
                });
                $grid->column('admin_name', '操作人')->display(function () {
                    if (!$this->admin_id) {
                        return '暂无';
                    } else {
                        return Admin::user()->find($this->admin_id)->name;
                    }
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->append('<a href="/admin/NewbornZone/BUser/'.$this->row->city.'" ><i class="fa fa-info-circle">查看</i></a>');
                });
            }
        );
        return $content->header('新人专区用户池')->row($gridList);
    }

    public function cityUser(Request $request, Content $content, $cityName) {
        $pageSize = $request->input('per_page', self::PAGE_SIZE);
        $page = $request->input('page', 1);
        $request = $request->all();
        $condition = [];
        if (!empty($request['uid'])) {
            $condition['uid'] = $request['uid'];
        }
        if (!empty($request['nick'])) {
            $uid = mMember::getUidByNick($request['nick']);
            if (!empty($uid)) {
                $condition['uid'] = $uid;
            }
        }
        if (!empty($request['user_type'])) {
            $condition['user_type'] = $request['user_type'];
        }
        $condition['city'] = $cityName;
        $condition['data_status'] = mNewbornZoneBUser::STATUS_NORMAL;
        $total = mNewbornZoneBUser::count($condition);
        $condition['ORDER'] = [
            'edit_time' => 'DESC',
            'id' => 'DESC'
        ];
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize,
        ];
        $userList = mNewbornZoneBUser::select('*', $condition);
        $uids = array_column($userList, 'uid');
        $memberList = sMember::getUserInfoByUserIds($uids);
        $uidInfoMap = array_column($memberList, null, 'uid');
        // 获取到期时间
        $designerUids = [];
        $decoUids = [];
        foreach ($userList as $userItem) {
            if ($userItem['user_type'] == mNewbornZoneBUser::USER_TYPE_DESIGNER) {
                $designerUids[] = $userItem['uid'];
            } else {
                $decoUids[] = $userItem['uid'];
            }
        }
        if ($designerUids) {
            $designerAuthList = DesignerAuth::getByUserIds($designerUids);
            $designerUidExpireTimeMap = array_column($designerAuthList, 'expire_time', 'uid');
        }
        if ($decoUids) {
            $decoAuthList = DecoCompanyAuth::select('*', ['uid' => $decoUids]);
            $decoUidExpireTimeMap = array_column($decoAuthList, 'auth_expire_time', 'uid');
        }
        // 获取近7天咨询用户数
        $startTime = time() - 7*24*60*60;
        $consultUserList = mNewbornZoneWelfareInfo::getConsultUserNumByTimeRange($startTime, time());
        $userConsultNumList = [];
        foreach ($consultUserList as $consultUserItem) {
            $bUids = explode(',', $consultUserItem['bind_uids']);
            if ($curBUids = array_intersect($bUids, $uids)) {
                foreach ($curBUids as $curBUid) {
                    $userConsultNumList[$curBUid][] = $consultUserItem['uid'];
                }
            }
        }
        foreach ($userList as &$userItem) {
            $userItem['nick'] = $uidInfoMap[$userItem['uid']]['nick'];
            if ($userItem['user_type'] == mNewbornZoneBUser::USER_TYPE_DESIGNER) {
                $userItem['user_type'] = '设计师';
                $userItem['expire_date'] = !empty($designerUidExpireTimeMap[$userItem['uid']]) ? date('Y-m-d H:i:s', $designerUidExpireTimeMap[$userItem['uid']]) : '';
            } else {
                $userItem['user_type'] = '装企';
                $userItem['expire_date'] = !empty($decoUidExpireTimeMap[$userItem['uid']]) ? date('Y-m-d H:i:s', $decoUidExpireTimeMap[$userItem['uid']]) : '';
            }
            $userItem['auth_status'] = $uidInfoMap[$userItem['uid']]['type'] == mMember::USER_COMMON ? '已过期' : '已认证';
            $userItem['consult_user_num'] = $userConsultNumList[$userItem['uid']] ? count(array_unique($userConsultNumList[$userItem['uid']])) : 0;
        }
        $gridModel = new pGridDataModel($userList, $total, [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(4, function ($filter) {
                        $filter->equal('uid', '用户UID')->placeholder('请输入uid');
                    });
                    $filter->column(4, function ($filter) {
                        $filter->equal('nick', '用户昵称')->placeholder('请输入昵称');
                    });
                    $filter->column(4, function ($filter) {
                        $filter->equal('user_type', '用户类型')->select([mNewbornZoneBUser::USER_TYPE_DESIGNER => '设计师', mNewbornZoneBUser::USER_TYPE_DECO => '装企']);
                    });
                    $filter->expand();
                });

                $grid->column('uid', '用户ID');
                $grid->column('nick', '用户昵称');
                $grid->column('user_type', '用户类型');
                $grid->column('auth_status', '认证状态');
                $grid->column('expire_date', '认证到期时间');
                $grid->column('add_time', '入池时间')->display(function () {
                    return date('Y-m-d H:i:s', $this->edit_time);
                });
                $grid->column('consult_user_num', '近7日已咨询用户数');
                $grid->column('admin_name', '操作人')->display(function () {
                    if (!$this->admin_id) {
                        return '暂无';
                    } else {
                        return Admin::user()->find($this->admin_id)->name;
                    }
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                });
            }
        );
        return $content->header("{$cityName}地区")
            ->breadcrumb(
                ['text' => "新人专区用户池", 'url' => "/NewbornZone/BUser/index"],
                ['text' => "{$cityName}地区"],
            )->row($gridList);
    }

    public function create(Request $request, Content $content, $city) {
        $form = new Form();
        $form->textarea('b_uids', 'B端用户UID')
            ->placeholder('支持英文逗号隔开批量填写用户uid，例如：xxx,xxx,xxx')
            ->required()
            ->help('提交时自动对当前地区用户池进行去重，已有的用户则自动删除');
        $form->confirm('确定提交吗？');
        $form->action("/admin/NewbornZone/BUser/{$city}/save");

        $header = "{$city}地区B端用户添加";
        $tab = new Tab();
        $tab->add($header, $form->render());
        return $content->header($header)
            ->breadcrumb(
                ['text' => "{$city}地区B端用户列表", 'url' => "/NewbornZone/BUser/{$city}"],
                ['text' => "{$city}地区B端用户添加"],
            )->row($tab);
    }

    public function save(Request $request, $city) {
        $bUids = $request->input('b_uids');
        if (empty($bUids)) {
            $error = new MessageBag(['title' => 'B端用户UID不可为空']);
            return back()->with(compact('error'));
        }
        $bUidsArr = array_unique(array_map(function ($bUid) {
            return trim($bUid);
        }, explode(',', $bUids)));
        // 校验是否是装修公司和设计师
        $userList = sMember::getUserInfoByUserIds($bUidsArr);
        $uidInfoMapList = !empty($userList) ? array_column($userList, null, 'uid') : [];
        $bUserData = [];
        $designerNum = 0;
        $decoNum = 0;
        $existUserList = mNewbornZoneBUser::getAllCityUserList($city);
        $uidExistUserMap = array_column($existUserList, null, 'uid');
        foreach ($bUidsArr as $bUid) {
            if (empty($uidInfoMapList[$bUid]) || !in_array($uidInfoMapList[$bUid]['type'], [mMember::AUTH_USER_DESIGNER, mMember::AUTH_DECO_COMPANY])) {
                $error = new MessageBag(['title' => "uid-{$bUid}不是设计师也不是装修公司，请移除"]);
                return back()->with(compact('error'));
            }
            // 去除已存在uid
            if (!empty($uidExistUserMap[$bUid]) && $uidExistUserMap[$bUid]['data_status'] == mNewbornZoneBUser::STATUS_NORMAL) {
                continue;
            }
            if ($uidInfoMapList[$bUid]['type'] == mMember::AUTH_USER_DESIGNER) {
                $designerNum ++;
                $userType = mNewbornZoneBUser::USER_TYPE_DESIGNER;
            } else {
                $decoNum ++;
                $userType = mNewbornZoneBUser::USER_TYPE_DECO;
            }
            if (!empty($uidExistUserMap[$bUid]) && $uidExistUserMap[$bUid]['data_status'] == mNewbornZoneBUser::STATUS_DELETE) {
                $updateBUserData[] = $bUid;
            } else {
                $addBUserData[] = [
                    'city' => $city,
                    'uid' => $bUid,
                    'user_type' => $userType,
                    'admin_id' => Admin::user()->id,
                    'add_time' => time(),
                    'edit_time' => time(),
                    'data_status' => mNewbornZoneBUser::STATUS_NORMAL
                ];
            }
        }
        // 添加
        if (!empty($addBUserData)) {
            if (!mNewbornZoneBUser::dataMultiInsert($addBUserData)) {
                $error = new MessageBag(['title' => 'B端用户批量写入失败']);
                return back()->with(compact('error'));
            }
        }
        // 更新
        if (!empty($updateBUserData)) {
            if (!mNewbornZoneBUser::dataUpdate([
                'data_status' => mNewbornZoneBUser::STATUS_NORMAL,
                'edit_time' => time(),
                'admin_id' => Admin::user()->id
            ], ['uid' => $updateBUserData, 'city' => $city])) {
                $error = new MessageBag(['title' => 'B端用户批量更新失败']);
                return back()->with(compact('error'));
            }
        }
        // 更改数量
        $cityItem = mNewbornZoneBCity::getCityItem($city);
        $userNumData = [
            'designer_num' => $cityItem ? $cityItem['designer_num'] + $designerNum : $designerNum,
            'deco_num' => $cityItem ?  $cityItem['deco_num'] + $decoNum : $decoNum,
            'admin_id' => Admin::user()->id
        ];
        if (!mNewbornZoneBCity::updateCityDataByCity($city, $userNumData)) {
            $error = new MessageBag(['title' => 'B端用户地区数量更新失败']);
            return back()->with(compact('error'));
        }
        $success = new MessageBag(['title' => '操作成功']);
        return redirect("/admin/NewbornZone/BUser/{$city}")->with(compact('success'));
    }

    public function del($city, $id) {
        $bUser = mNewbornZoneBUser::getUserById($id);
        if ($bUser) {
            // 查看当前地区的B端用户数量，不得少于2个
            $cityInfo = mNewbornZoneBCity::getCityItem($city);
            if ($bUser['user_type'] == mNewbornZoneBUser::USER_TYPE_DESIGNER && $cityInfo['designer_num'] <= 2) {
                return response()->json([
                    'status' => false,
                    'message' => '设计师数量不得少于2个',
                ]);
            }
            if ($bUser['user_type'] == mNewbornZoneBUser::USER_TYPE_DECO && $cityInfo['deco_num'] <= 1) {
                return response()->json([
                    'status' => false,
                    'message' => '装修公司数量不得少于1个',
                ]);
            }
            if (!mNewbornZoneBUser::removeBUser($id, Admin::user()->id)) {
                return response()->json([
                    'status' => false,
                    'message' => '操作失败',
                ]);
            }
            // 更新数量
            $cityData = [
                'admin_id' => Admin::user()->id
            ];
            if ($bUser['user_type'] == mNewbornZoneBUser::USER_TYPE_DESIGNER) {
                $cityData['designer_num'] = $cityInfo['designer_num']-1;
            } else {
                $cityData['deco_num'] = $cityInfo['deco_num']-1;
            }
            if (!mNewbornZoneBCity::updateCityDataById($cityInfo['id'], $cityData)) {
                return response()->json([
                    'status' => false,
                    'message' => '数量更新失败',
                ]);
            }
        } else {
            return response()->json([
                'status' => false,
                'message' => '该用户不存在',
            ]);
        }
    }

}
